<template>
   <div class="sub-filter">
     <div class="item" v-for="item in list" :key="item.id">
       <div class="head">{{item.name}}</div>
       <div class="body">
         <a href="javascript:;" @click="fitlerFn(item,{})" :class="{active : !item.activeName || item.activeName=== null}">全部</a>
         <a href="javascript:;" :class="{active :item.activeName=== item2.name}" v-for="item2 in item.properties" :key="item2.id" @click="fitlerFn(item,item2)">{{item2.name}}</a>
       </div>
     </div>
   </div>
</template>

<script>
import { inject, computed, toRef } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    const subCate = inject('subCate')
    const sortParams = inject('sortParams')
    const brands = inject('brands')
    // 由于品牌和下面的规格不在同一个地方，但数据渲染时又是一样的，所以需要数据改造
    const list = computed(() => {
      return [brands.value, ...subCate.value.saleProperties]
    })
    // 筛选范围
    const attrs = toRef(sortParams, 'attrs')
    const brandId = toRef(sortParams, 'brandId')
    const setList = inject('setList')
    const fitlerFn = (theItem, theProp) => {
      theItem.activeName = theProp.name
      if (theItem.name === '品牌') {
        brandId.value = theProp.id
        return
      }
      const index = attrs.value.findIndex(item => item.groupName === theItem.name)
      if (index === -1) {
        attrs.value.push({ groupName: theItem.name, propertyName: theItem.activeName })
      } else {
        attrs.value[index].propertyName = theItem.activeName
      }
      attrs.value = attrs.value.filter(item => item.propertyName)
      setList()
    }
    return { subCate, list, fitlerFn }
  }
}
</script>

<style scoped lang='less'>
  // 筛选区
  .sub-filter {
    background: #fff;
    padding: 25px;
    .item {
      display: flex;
      line-height: 40px;
      .head {
        width: 80px;
        color: #999;
      }
      .body {
        flex: 1;
        a {
          margin-right: 36px;
          transition: all .3s;
          display: inline-block;
          &.active,
          &:hover {
            color: @xtxColor;
          }
        }
      }
    }
  }
</style>
